const cloudbase = require('@cloudbase/node-sdk');
const axios = require('axios');

exports.main = async (event, context) => {
    try {
        // 初始化云开发环境
        const app = cloudbase.init({
            env: 'your_cloud_env_id'
        });
        console.log('初始化云开发SDK完成');

        // 检查URL参数
        if (!event.url) {
            return {
                success: false,
                message: '缺少URL参数'
            };
        }

        // 下载URL内容
        const response = await axios.get(event.url, {
            responseType: 'arraybuffer'
        });

        // 生成随机文件名
        const fileName = `downloads/${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
        const fileExtension = event.url.split('.').pop().split('?')[0].toLowerCase();
        const fullFileName = `${fileName}.${fileExtension}`;

        // 上传到云存储
        const uploadResult = await app.uploadFile({
            cloudPath: fullFileName,
            fileContent: response.data
        });

        // 获取文件访问链接
        const fileUrl = await app.getTempFileURL({
            fileList: [fullFileName]
        });

        return {
            success: true,
            fileUrl: fileUrl.fileList[0].tempFileURL,
            fileId: uploadResult.fileID
        };
    } catch (error) {
        console.error('云函数执行错误:', error);
        return {
            success: false,
            message: error.message,
            error: {
                name: error.name,
                message: error.message,
                stack: error.stack,
                code: error.code
            }
        };
    }
};